<template>

  <el-tree
    ref="Tree"
    :data="TreeData"
    show-checkbox
    node-key="id"
    :props="props"
    :default-checked-keys="checked"
    :expand-on-click-node="true"
  />

</template>

<script>
export default {
  name: 'BossTree',
  props: {
    dialogType: {
      type: String,
      default: 'VIEW'
    },
    checked: {
      type: Array,
      default: () => { return [] }
    },
    resource: {
      type: Array,
      default: () => { return [] }
    },
    lable: {
      type: String,
      default: 'name'
    },
    children: {
      type: String,
      default: 'children'
    },
    leaf: {
      type: String,
      default: 'leaf'
    },
    parentDefine: {
      type: String,
      default: 'parentId'
    }

  },
  data() {
    return {
      props: {
        label: this.lable,
        children: this.children,
        isLeaf: this.leaf
      },
      TreeData: []
    }
  },
  watch: {
    resource: {
      handler(val, oldVal) {
        if (val !== []) { this.TreeData = this.buildTree(this.resource) }
      },
      deep: true
    }
  },
  mounted() {
    this.initUI()
  },
  methods: {
    /**
     * 界面初始化
     */
    initUI() {
      this.TreeData = []
    },
    getCheckedKey() {
      return this.$refs.Tree.getCheckedKeys()
    },
    /**
     * 根据后端数据建立树结构
     * @param {*} nodes
     */
    buildTree(nodes) {
      // 将包信息转换成以id为键的对象
      const nodeMap = {}
      nodes.forEach(node => {
        // 当前状态为查看时，禁止选择
        if (this.dialogType === 'VIEW') { node.disabled = true }
        nodeMap[node.id] = node
      })

      // 构建树结构
      const tree = []
      nodes.forEach(node => {
        if (node[this.parentDefine] === '-1') {
          // 没有父节点，说明是根节点
          tree.push(node)
        } else {
          // 有父节点，将当前节点添加到父节点的children中
          const parent = nodeMap[node[this.parentDefine]]
          if (parent) {
            if (!parent[this.children]) {
              parent[this.children] = []
            }
            parent[this.children].push(node)
          }
        }
      })

      return tree
    }
  }}
</script>

